/*
 * @lc app=leetcode.cn id=92 lang=javascript
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
var reverseBetween = function (head, left, right) {
  if (head === null || head.next === null) {
    return head;
  }

  const reverseNode = (head, n) => {
    let pre = null;
    let cur = head;
    while (n--) {
      let next = cur.next;
      cur.next = pre;
      pre = cur;
      cur = next;
    }
    head.next = cur;
    return pre;
  };

  const dummp = new ListNode(0, head);
  const n = right - left + 1;
  let p = dummp;
  while (--left) {
    p = p.next;
  }
  p.next = reverseNode(p.next, n);

  return dummp.next;
};
// @lc code=end
